// TcpStreamReassembler.java 的更新
package com.example.netcapture.utils;

import com.example.netcapture.entity.PacketInfo;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TcpStreamReassembler {

    public static String getTcpStream(String sessionId) {
        TcpSessionManager.TcpSession session = TcpSessionManager.getOrCreateSession(sessionId);
        return session.getReassembledStream();
    }

    public static Map<String, String> getAllTcpStreams() {
        Map<String, String> streams = new HashMap<>();
        // 获取所有会话的完整数据流
        // 实现遍历所有session并调用getReassembledStream()
        return streams;
    }

    // 重组TCP数据的核心逻辑
    public static String reassembleTcpData(List<PacketInfo> packets) {
        if (packets == null || packets.isEmpty()) {
            return "";
        }

        // 1. 按序列号排序
        packets.sort(Comparator.comparingLong(PacketInfo::getTcpSeqNumber));

        StringBuilder streamData = new StringBuilder();
        long expectedSeq = -1;

        // 2. 按顺序提取负载数据，处理序列号连续性
        for (PacketInfo packet : packets) {
            if (packet.getPayload() != null) {
                String payload = packet.getPayload();

                // 检查序列号连续性
                long currentSeq = packet.getTcpSeqNumber();
                if (expectedSeq != -1 && currentSeq != expectedSeq) {
                    // 序列号不连续，可能有丢包，这里可以添加日志
                }

                // 更新期望的下一个序列号
                expectedSeq = currentSeq + payload.length();

                if (isValidPayload(payload)) {
                    streamData.append(payload);
                }
            }
        }

        return streamData.toString();
    }

    private static boolean isValidPayload(String payload) {
        if (payload == null || payload.trim().isEmpty()) {
            return false;
        }
        // 可以根据需要添加更多的验证逻辑
        return true;
    }
}